package com.xce.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @ClassName GlobalFiter
 * @Description TODO
 * @Author lld
 * @Date 2025/7/8 2:38
 * @Version 1.0
 */

@Slf4j
@Component
public class GlobalFiter implements GlobalFilter, Ordered {
    // filter逻辑处理
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        // ------------------前置处理------------------
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String url = request.getURI().toString();
        long startTime = System.currentTimeMillis();
        log.info("请求地址：{}, 开始时间{}",url,startTime);
        // 放行
        return chain.filter(exchange)
                .doFinally(signalType -> {
            // ------------------后置处理------------------
            long endTime = System.currentTimeMillis();
            log.info("结束请求，时间：{},耗时：{}ms",endTime,endTime-startTime);
        });
    }

    // 优先级
    @Override
    public int getOrder() {
        return 0;
    }
}
